package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.OrderInfo;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService    orderService;

    @Autowired
    private JedisPool jedisPool;

    @PostMapping("/toOrder")
    public Result toOrder(@RequestBody Map map){
        //1.从redis中根据用户的手机号和RedisMessageConstant类的后缀来获得用户验证码。
        String telephone = (String) map.get("telephone");
        Jedis jedis = jedisPool.getResource();
        String code = jedis.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = (String) map.get("validateCode");
        jedis.close();
        //2.验证码进行对比
        if (code == null || code.length() == 0 || !validateCode.equals(code)){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //3.调用service来添加用户的预约订单数据
        Result result = null;
        try {
            map.put("orderType",Order.ORDERTYPE_WEIXIN);
            result = orderService.toOrder(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约服务器异常，请稍后再试");
        }
        //4.如果添加用户预约订单数据成功，需要给用户发送预约成功的短
        if(result.isFlag()){
            String orderDate = (String) map.get("orderDate");
            try {
                SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,orderDate);
            } catch (ClientException e) {
                e.printStackTrace();
                return new Result(false,"预约服务器异常，请稍后再试");
            }
        }
        return result;
    }
    @PostMapping("/findById")
    public Result findById(Integer id){
        try {
            OrderInfo orderInfo = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,orderInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
